// 云函数模板
// 部署：在 cloud-functions/login 文件夹右击选择 “上传并部署”

const cloud = require('wx-server-sdk')

// 初始化 cloud
cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: cloud.DYNAMIC_CURRENT_ENV
})

/**
 * 这个示例将经自动鉴权过的小程序用户 openid 返回给小程序端
 * 
 * event 参数包含小程序端调用传入的 data
 * 
 */
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let { OPENID, APPID, UNIONID } = wxContext
  let { avatarUrl, nickName } = event
  const db = cloud.database()
  var success = false
  var message = "登录失败"
  var resp = {}
  var user = await db.collection('user').where({
    _openid: OPENID // 填入当前用户 openid
  }).get()

  if (user.data.length != 0) {
    var updeteResp = await db.collection('user').where({
      _openid: OPENID // 填入当前用户 openid
    }).update({
      data: {
        _openid: OPENID,
        avatarUrl: avatarUrl
      }
    }).then(res => {
      console.log("update:", res)
      success = true
      message = "登录成功"
      resp = user.data[0]
    }, error => {
      success = false
      message = "失败"
    })
  } else {
    var addResp = await db.collection('user').add({
      data: {
        _openid: OPENID,
        avatarUrl: avatarUrl,
        nickName: nickName,
        isCoach: false,
        isOut:false,
        point: 0,
        isMember:false
      }
    }).then(res => {
      id = res._id
      console.log("add:", res)
      success = true
      message = "登录成功"
      resp = {
        _id: id,
        _openid: OPENID,
        avatarUrl: avatarUrl,
        nickName: nickName,
        isCoach: false,
        point: 0
      }
    }, error => {
      success = false
      message = "登录失败"
    })
  }

  return {
    success: success,
    message: message,
    data: resp
  }
}

